package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * projectName: com.atguigu.tingshu.album.receiver
 *
 * @author: 吴振鹏
 * description:监听消息
 * time: 2025/9/9 16:38
 */
@Slf4j
@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", autoDelete = "false"),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateTrackStat(String msg, Message message, Channel channel) {


        try {
            if(!StringUtils.isEmpty( msg)){
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);

                //获取业务编号，防止重复消费
                String businessNo = trackStatMqVo.getBusinessNo();

                //执行成功，说明是第一次消费
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 10, TimeUnit.MINUTES);
                if(result) {
                    try {
                        trackInfoService.updateTrackStat(trackStatMqVo);
                    } catch (Exception e) {
                        //异常，删除上一个key
                        this.redisTemplate.delete(businessNo);
                        log.error(e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        // 手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("消息确认失败：" + e.getMessage(), e);
        }

    }

}
